<?php
/**
 * 工单每日回复
 * User: Administrator
 * Date: 2018\8\8 0008
 * Time: 11:50
 */

namespace app\lib\Order\OrderOption;


use app\lib\Order\IsOrder\IsOrder;
use app\lib\Order\OrderConstructionLog\AddOrderConstructionImg;
use app\lib\Order\OrderConstructionLog\AddOrderConstructionLog;
use app\lib\Order\OrderConstructionLog\UpdateOrderConstructionLog;
use app\lib\Order\OrderExtensionConfig\GetOrderBindingExtension;
use app\lib\Order\OrderExtensionConfig\OrderBindingEditExtension;

class OrderReplyOption
{
    protected $orderId;
    protected $opUid;
    protected $replyId;
    protected $imgArray;
    protected $content;
    /*延期配置id*/
    protected  $extensionId = 0;
    public function __construct($orderId,$opUid)
    {
        $this->orderId = $orderId;
        $this->opUid   = $opUid;
    }
    public function setReplyId($replyId){
        $this->replyId = $replyId;
        return $this;
    }

    public function setImg($img){
        $this->imgArray = $img;
        return $this;
    }

    public function setContent($content){
        $this->content = $content;
        return $this;
    }
    public function setExtensionId($extensionId){
        $this->extensionId = $extensionId;
        return $this;
    }

    /**
     * 参数验证
     * @throws \Exception
     */
    protected function check(){
        $isOrder = new IsOrder($this->orderId);
        /*状态是否需要提交工地日志*/
        if(!$isOrder->isExecuteOrder()){
            exception('工单状态异常无法回访');
        }
        /*是否存在标签需要提交工地日志*/
        $model =  new GetOrderBindingExtension($this->orderId);

        if($model->isOrderBindingPay()){
            exception('该工单在被催款,无需回复工地日志');
        };
        if($model->isOrderBindingSign()){
            exception('该工单在被等待验收,无需回复工地日志');
        };
        if(empty($this->content)){
            exception('提交工地日志内容不能为空');
        }
        return true;
    }

    /**
     * 工单每日回复
     * @return bool
     * @throws \Exception
     */
    public function save(){
        if(empty($this->replyId)){
             $this->replyId =  (new AddOrderConstructionLog())->setContent($this->content)
                ->setOpUid($this->opUid)->setOrderId($this->orderId)->setExtensionId($this->extensionId)->save();
        }else{
            (new UpdateOrderConstructionLog())->setContent($this->content)
                ->setOpUid($this->opUid)->setOrderId($this->orderId)->setId($this->replyId)->save();
        }
        if($this->imgArray){
            foreach ($this->imgArray as $k=>$v){
                (new AddOrderConstructionImg($this->replyId,$v,$this->opUid))->save();
            }
        }
        $model =  new GetOrderBindingExtension($this->orderId);
        /*如果存在普通标签回复就取消掉标签*/
        if($model->isOrderBindingDaily()){
            (new OrderBindingEditExtension($this->orderId,'reply','主动回复工地日志，取消标签'))->releaseBinding();
        }
        return true;
    }





}